import React, { useEffect, useState } from "react";
import { PageHeader, Descriptions, message } from "antd";
import axios from "axios";
import moment from "moment";
import { HeartTwoTone } from "@ant-design/icons";

export default function Detail(props) {
  const [newDetail, setNewDetail] = useState(null);
  useEffect(() => {
    axios
      .get(`/news/${props.match.params.id}?_expand=category`)
      .then(({ data }) => {
        data.view = data.view + 1;
        setNewDetail(data);
        return data.view;
      })
      .then(res => {
        axios.patch(`/news/${props.match.params.id}`, {
          view: res
        });
      });
  }, [props.match.params.id]);
  const handleStar = () => {
    axios
      .patch(`/news/${props.match.params.id}`, {
        start: newDetail.start + 1
      })
      .then(() => {
        newDetail.start = newDetail.start + 1;
        setNewDetail({ ...newDetail });
        message.success("点赞成功~");
      });
  };
  return (
    <div>
      {newDetail && (
        <PageHeader
          ghost={false}
          onBack={() => window.history.back()}
          title={newDetail.title}
          subTitle={
            <div>
              {newDetail.category.title}&nbsp;&nbsp;
              <HeartTwoTone
                twoToneColor="#eb2f96"
                onClick={() => {
                  handleStar();
                }}
              />
            </div>
          }
        >
          <Descriptions size="small" column={3}>
            <Descriptions.Item label="创建者">
              {newDetail.author}
            </Descriptions.Item>
            <Descriptions.Item label="发布时间">
              {newDetail.publishTime
                ? moment(newDetail.publishTime).format("YYYY-MM-DD HH:mm:ss")
                : "-"}
            </Descriptions.Item>
            <Descriptions.Item label="区域">
              {newDetail.region}
            </Descriptions.Item>
            <Descriptions.Item label="访问数量">
              {newDetail.view}
            </Descriptions.Item>
            <Descriptions.Item label="点赞数量">
              {newDetail.start}
            </Descriptions.Item>
            <Descriptions.Item label="评论数量">0</Descriptions.Item>
          </Descriptions>
          <div
            dangerouslySetInnerHTML={{ __html: newDetail.content }}
            style={{
              minHeight: "200px",
              marginTop: "20px",
              padding: "10px",
              border: "1px solid #f1f1f1"
            }}
          ></div>
        </PageHeader>
      )}
    </div>
  );
}
